package com.xjm.ips.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjm.ips.entity.AjaxJson;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Component
public class VerifyCodeFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if("POST".equals(request.getMethod()) && "/doLogin".equals(request.getServletPath())){
            //如果是登录请求
            String requestCode = request.getParameter("code");
            String verifyCode = ((String) request.getSession().getAttribute("verifyCode"));
            if(StringUtils.isBlank(requestCode) || !StringUtils.equalsIgnoreCase(verifyCode,requestCode)){
                //验证码校对失败
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                AjaxJson error = AjaxJson.error("错误的验证码!");
                out.write(new ObjectMapper().writeValueAsString(error));
                out.flush();
                out.close();
                return;
            }
        }
        filterChain.doFilter(request,response);
    }
}
